package com.lhd.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lhd.app.func.TableProcessFunction;
import com.lhd.bean.TableProcess;
import com.lhd.common.utils.MyKafkaUtil;
import com.lhd.common.utils.MyPhoenixSink;
import com.lhd.common.utils.MysqlUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class DimApp {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

//         env.enableCheckpointing(5*60000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(10*60000L);
//        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
//        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,5000L));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/211126/ck");
//        System.setProperty("HADOOP_USER_NAME","ROOT");

        DataStreamSource<String> ds = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer("topic_db", "dimapp"));

        SingleOutputStreamOperator<JSONObject> filterJSONDS = ds.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
//                    保留新增及变化及初始化数据
                    String type = jsonObject.getString("type");
                    if (type.equals("insert") || type.equals("update") || type.equals("bootstrap-insert")) {
                        out.collect(jsonObject);
                    }
                } catch (Exception e) {
                    System.out.println("错误数据不是json数据:" + value);
                }
            }
        });
        DataStream<String> mysqlDs = MysqlUtil.cdcMysql(env, "gmall_config", "table_process");
//        mysqlDs.print("FlinkCDC:");
        MapStateDescriptor<String, TableProcess> mapState = new MapStateDescriptor<>("mapState", String.class, TableProcess.class);

        BroadcastStream<String> broadcastStream = mysqlDs.broadcast(mapState);

        BroadcastConnectedStream<JSONObject, String> connect = filterJSONDS.connect(broadcastStream);

        SingleOutputStreamOperator<JSONObject> dimDS = connect.process(new TableProcessFunction(mapState));

        dimDS.print("最终结果--------->");
        dimDS.addSink(new MyPhoenixSink());

        env.execute();
    }
}
